from flask import g
from flask import request

from info import constants, db
from info.models import User, Category, News
from info.utils.response_code import RET
from . import news_blue
from flask import session, render_template, current_app, jsonify
from info.utils.commons import login_required

@news_blue.route('/')
@login_required
def index():

    user = g.user
    # 新闻分类数据
    # 查询mysql中的新闻分类数据
    try:
        caregories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询分类数据失败')
    # 判断查询结果
    if not caregories:
        return jsonify(errno=RET.NODATA,errmsg='无新闻分类数据')
    # 遍历查询结果
    caregory_list = []
    for caregory in caregories:
        caregory_list.append(caregory.to_dict())

    # 新闻点击排行
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻排行数据失败')
    #判断查询结果

    if not news_list:
        return jsonify(errno=RET.DBERR,errmsg='无新闻排行数据')
    news_click_list = []
    for news in news_list:
        news_click_list.append(news.to_dict())

    # 定义字典数据，传给模板
    data = {
        'user_info':user.to_dict() if user else None,
        'category_list': caregory_list,
        'news_click_list':news_click_list
    }
    return render_template('news/index.html',data=data)


@news_blue.route('/news_list')

def get_new_list():
    # 获取参数
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '10')
    try:
        cid, page, per_page = int(cid), int(page), int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数类型错误')
    # 根据新闻分类查询数据
    filters =[]
    # 如果新闻分类id不是最新
    if cid > 1:
        filters.append(News.category_id == cid)
    # 根据新闻分类查询数据库
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻列表数据失败')
    # 使用分页对象获取分页后的新闻数据
    news_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page
    # 遍历新闻列表，调用模型类的to——dict方法，获取详细的新闻数据
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_dict())
    # 定义容器返回数据
    data = {
        'news_dict_list': news_dict_list,
        'total_page': total_page,
        'current_page': current_page
    }
    return jsonify(errno=RET.OK,errmsg='OK',data=data)


@news_blue.route('/<int:news_id>')
@login_required
def get_news_detail(news_id):

    # # redis获取user_id
    # user_id = session.get('user_id')
    # # 如果use——id存在，查询mysql
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user

    # 新闻点击排行
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询新闻排行数据失败')
    # 判断查询结果

    if not news_list:
        return jsonify(errno=RET.DBERR, errmsg='无新闻排行数据')
    news_click_list = []
    for news in news_list:
        news_click_list.append(news.to_dict())



    #新闻详情数据展示
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻详情数据失败')
    # 判断查询结果：
    if not news:
        return jsonify(errno=RET.NODATA,errmsg='无新闻详情数据')

    # 判断是否收藏
    is_collected = False
    if user and news in user.collection_news:
        is_collected = True

    data = {
        'user_info': user.to_dict() if user else None,
        'news_click_list': news_click_list,
        'news_detail':news.to_dict(),
        'is_collected': is_collected

    }
    return render_template('news/detail.html', data=data)




@news_blue.route('/news_collect',methods=['POST'])
@login_required
def news_collect():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登陆')

    news_id = request.json.get('news_id')
    action = request.json.get('action')

    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不完整')

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数类型错误')
    if action not in ['collect','cancel_collect']:
        return jsonify(errno=RET.PARAMERR,errmsg='参数格式错误')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻数据失败')
    if not news:
       return jsonify(errno=RET.NODATA,errmsg='无新闻数据')
    if action == 'collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        user.collection_news.remove(news)

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')


    return jsonify(errno=RET.OK,errmsg='OK')




















# 项目logo图标加载
@news_blue.route('/favicon.ico')
def favicon():
    # 通过current_app调用Flask框架内部的发送静态文件给浏览器的函数send_static_file
    return current_app.send_static_file("news/favicon.ico")